#include "../logsys/log.hpp"

// 扩展：滚动文件方向（以时间为主导）
enum TimeGap
{
    GAP_SECOUND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

class RollSinkByTime : public XKL::LogSink
{
public:
    RollSinkByTime(const std::string &basename, TimeGap gap)
        : _basename(basename)
    {
        switch (gap)
        {
        case GAP_SECOUND:
            _time_gap = 1;
            break;
        case GAP_MINUTE:
            _time_gap = 60;
            break;
        case GAP_HOUR:
            _time_gap = 3600;
            break;
        case GAP_DAY:
            _time_gap = 3600 * 24;
            break;
        }
        time_t ctime = XKL::Util::Date::Current();
        _cur_time = (_time_gap == 1) ? ctime : ctime % _time_gap;

        std::string filename = CreateFileName();
        XKL::Util::File::CreateDirectory(XKL::Util::File::Path(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }

    void Log(const char *data, size_t len) override
    {
        time_t ctime = XKL::Util::Date::Current();
        if ((ctime % _time_gap) != _cur_time)
        {
            _ofs.close();
            _cur_time = (_time_gap == 1) ? ctime : ctime % _time_gap;
            _ofs.open(CreateFileName(), std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }

        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    std::string CreateFileName()
    {
        time_t ctime = XKL::Util::Date::Current();
        struct tm cur;
        localtime_r(&ctime, &cur);

        std::stringstream filename;
        filename << _basename;
        filename << cur.tm_year + 1900;
        filename << cur.tm_mon + 1;
        filename << cur.tm_mday;
        filename << cur.tm_hour;
        filename << cur.tm_min;
        filename << cur.tm_sec;
        filename << ".log";

        return filename.str();
    }

private:
    std::string _basename;
    size_t _cur_time;
    size_t _time_gap;
    std::ofstream _ofs;
};

int main()
{
    std::unique_ptr<XKL::LoggerBuilder> builder(new XKL::GlobalLoggerBuilder());
    builder->BuildLoggerLevel(XKL::LogLevel::DEBUG);
    builder->BuildLoggerName("sync-logger");
    builder->BuildLoggerType(XKL::LoggerType::LOGGER_SYNC);
    builder->BuildFormater("[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n");
    builder->BuildSink<RollSinkByTime>("./logfile/test-", GAP_SECOUND);
    XKL::Logger::ptr logger = builder->Build();
    
    time_t cur = XKL::Util::Date::Current();
    
    while(cur + 5 > XKL::Util::Date::Current())
    {
        logger->debug("日志测试");
        usleep(1000);
    }

    return 0;
}